package com.imay.live.activity.family;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.live.R;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.activity.family.controller.FamilyPersonController;
import com.imay.live.activity.family.manager.FamilyUserChangeManager;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.RepostHelper;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.model.FamilyUserInfo;
import com.imay.live.model.FamilyUserModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.dialog.ChoiseDialogFragment;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_CHANGE_ELDER;
import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_FOCUS;
import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_JOB_IN;
import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_JOB_OUT;
import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_NO_FOCUS;
import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_OUT;
import static com.imay.live.activity.family.controller.FamilyPersonController.MENU_ACTION_FAMILY_USER_REPOST;

/**
 * Created by Administrator on 2017/8/31 0031.
 */

public class FamilyPersonActivity extends BaseRequestActivity implements BaseQuickAdapter.OnItemChildClickListener, FamilyUserChangeManager.FamilyUserChangeListener {
    public static final String KEY_FAMILY_ID = "key_family_id";
    public static final String KEY_FAMILY_NICK = "key_family_nick";
    public static final String KEY_USER_STATUS = "key_user_status";

    public static final int OTHERS = 1;
    public static final int ME = 2;

    FamilyUserChangeManager manager;
    FamilyPersonController controller;
    FollowControl control;

    private String requestFamilyUserCommand, requestClearOutCommand, requestJobInCommand, requestJobOutCommand, requestChangeElderCommand;

    private int familyid;
    private String nick;

    private int start;
    private int count = 20;
    private int userStatus;

    private final int DEFALUT = 0;
    private final int REFRESH = 1;
    private final int LOADMORE = 2;

    private int refreshStatus = DEFALUT;

    /**
     * @param context
     * @param designation
     * @param status
     */
    public static void startActivity(Context context, int familyid, String designation, int status) {
        Intent intent = new Intent(context, FamilyPersonActivity.class);
        intent.putExtra(KEY_FAMILY_ID, familyid);
        intent.putExtra(KEY_FAMILY_NICK, designation);
        intent.putExtra(KEY_USER_STATUS, status);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_family_person;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        familyid = getIntent().getIntExtra(KEY_FAMILY_ID, -1);
        nick = getIntent().getStringExtra(KEY_FAMILY_NICK);
        userStatus = getIntent().getIntExtra(KEY_USER_STATUS, OTHERS);

        setTitle(R.string.str_family_person);
        if (userStatus == ME) {
            getTitleBar().setRightImageVisibility(false);
            getTitleBar().setRightTextVisibility(true);
            getTitleBar().addRightTextView(getString(R.string.str_family_person_level));
            getTitleBar().setRightTextOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FamilyUserLevelActivity.startActivity(FamilyPersonActivity.this);
                }
            });
        }
        controller = (FamilyPersonController) FamilyPersonController.Builder.create(this, FamilyPersonController.class).build();
        controller.initAdapter(userStatus);
        controller.setFamilyNick(nick);
        controller.setItemClick(this);

        controller.initRresh(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
                start = 0;
                refreshStatus = REFRESH;
                loadFamilyUsers();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                refreshStatus = LOADMORE;
                loadFamilyUsers();
            }
        });

        control = new FollowControl();

        manager = FamilyUserChangeManager.Builder.create(this).build();

        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
        start = 0;
        loadFamilyUsers();
    }

    private void loadFamilyUsers() {
        if (familyid == -1) {
            return;
        }
        requestFamilyUserCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyUsers(familyid, start, count)).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        if (command.equals(requestFamilyUserCommand)) {
            Result<FamilyUserModel> result = JSON.parseObject(data, new TypeReference<Result<FamilyUserModel>>() {
            }.getType());
            if (refreshStatus == REFRESH || refreshStatus == DEFALUT) {
                controller.setUserData(result.data);
                start = result.data.getFamilyUsers().size();
                if (refreshStatus == REFRESH) {
                    controller.finishRresh();
                }
                refreshStatus = DEFALUT;
            } else if (refreshStatus == LOADMORE) {
                controller.addUserData(result.data);
                start = start + result.data.getFamilyUsers().size();
                controller.finishLoadMore();
                refreshStatus = DEFALUT;
            }
        } else if (command.equals(requestClearOutCommand)) {
            FamilyUserChangeManager.userRefresh();
            ToastUtil.show(this, R.string.str_family_user_kiout_success);
        } else if (command.equals(requestJobInCommand)) {
            FamilyUserChangeManager.userRefresh();
            ToastUtil.show(this, R.string.str_family_user_joinin_success);
        } else if (command.equals(requestJobOutCommand)) {
            FamilyUserChangeManager.userRefresh();
            ToastUtil.show(this, R.string.str_family_user_joinout_success);
        } else if (command.equals(requestChangeElderCommand)) {
            FamilyUserChangeManager.elderChange();
            ToastUtil.show(this, R.string.str_family_user_change_success);
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        ErrorResult.toastError(this, code);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.rl_family_user_item:
                if (userStatus == OTHERS) {
                    return;
                }
                if (adapter.getItem(position) instanceof FamilyUserModel.FamilyUsersBean) {
                    final FamilyUserModel.FamilyUsersBean usersBean = (FamilyUserModel.FamilyUsersBean) adapter.getItem(position);
                    final int targetUid = usersBean.getUid();
                    final FamilyUserInfo.FamilyUserBean user = FamilyAccountManager.getInstance().getFamilyUserInfo().getFamilyUser();
                    controller.initMenu(user, usersBean, new ChoiseDialogFragment.OnItemClickListener() {
                        @Override
                        public void itemClick(int tagCallBack, int position, MenuItemModel itemModel) {
                            switch (itemModel.getAction()) {
                                case MENU_ACTION_FAMILY_USER_OUT: // 踢出
                                    DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.str_family_choise_kickout, usersBean.getNick()), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            requestClearOutCommand = controller.clearOut(targetUid);
                                        }
                                    });
                                    break;
                                case MENU_ACTION_FAMILY_USER_JOB_IN: // 任职
                                    DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.str_family_choise_jobin, usersBean.getNick()), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            requestJobInCommand = controller.jobin(targetUid);
                                        }
                                    });
                                    break;
                                case MENU_ACTION_FAMILY_USER_JOB_OUT: // 卸职
                                    DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.str_family_choise_jobout, usersBean.getNick()), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            requestJobOutCommand = controller.jobout(targetUid);
                                        }
                                    });
                                    break;
                                case MENU_ACTION_FAMILY_USER_CHANGE_ELDER: // 族长转移
                                    DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.str_family_choise_elderchange, usersBean.getNick()), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            requestChangeElderCommand = controller.changeElder(targetUid);
                                        }
                                    });
                                    break;
                                case MENU_ACTION_FAMILY_USER_NO_FOCUS: // 关注&取消关注
                                case MENU_ACTION_FAMILY_USER_FOCUS:
                                    controller.changeFoucus(control, usersBean);
                                    break;
                                case MENU_ACTION_FAMILY_USER_REPOST: // 举报
                                    controller.report(getSupportFragmentManager(), usersBean.getNick(), usersBean.getUid());
                                    break;
                            }
                        }
                    });
                }
                break;
            case R.id.iv_family_focus:
                if (userStatus == OTHERS) {
                    if (adapter.getItem(position) instanceof FamilyUserModel.FamilyUsersBean) {
                        final FamilyUserModel.FamilyUsersBean usersBean = (FamilyUserModel.FamilyUsersBean) adapter.getItem(position);
                        controller.changeFoucus(control, usersBean);
                    }
                }
                break;
            case R.id.iv_family_accept_head_img:
                if (userStatus == OTHERS) {
                    if (adapter.getItem(position) instanceof FamilyUserModel.FamilyUsersBean) {
                        final FamilyUserModel.FamilyUsersBean usersBean = (FamilyUserModel.FamilyUsersBean) adapter.getItem(position);
                        ProfileActivity.start(FamilyPersonActivity.this, usersBean.getUid());
                    }
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.unregisterFamilyNotify();
    }


    @Override
    public void elderChange() {
        start = 0;
        refreshStatus = REFRESH;
        loadFamilyUsers();
        FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
    }

    @Override
    public void userRefresh() {
        start = 0;
        refreshStatus = REFRESH;
        loadFamilyUsers();
    }
}
